package tables;


import java.util.HashMap;
import java.util.Map;

import fj.F;
import fj.data.Option;
import global.Global;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import server.Initialize;
import server.db.DatabaseFunctor;
import server.db.StmtHelper;
import server.objects.User;

import ajaxmethods.SessionMethod;

public class SaveForm extends SessionMethod {

	public static String url() {
		return Initialize.appURL()+"/ajaxCall.jsp?do="+SaveForm.class.getCanonicalName();
	}
	
	Integer idform;
	
	private F<Integer, DatabaseFunctor<Integer>> addContent = new F<Integer, DatabaseFunctor<Integer>>() {

		@Override
		public DatabaseFunctor<Integer> f(Integer formid) {
			idform=formid;
			link = Initialize.appURL()+"/act.jsp?do=external.SubmitForm&id="+formid+"&user="+global.getUser().id;
			String formContent ="<form action=\""+Initialize.appURL()+"/act.jsp?do=external.SubmitForm&id="+formid+"&user="+global.getUser().id+"\">"+content+"</form>";
			return StmtHelper.db("update form set content=").addVariable(formContent).addSql(", link=").addVariable(link)
				.addSql(" where idform=").addVariable(formid).executeUpdate();
		}
		
	};
	
	String content;
	String link;
	
	@Override
	public void perform(HttpServletRequest request,HttpServletResponse response)
	{
		super.perform(request, response);
		try {
			if(!data.has("notloggedin"))
			{
				String formtitle = request.getParameter("formtitle");
				content = request.getParameter("content");
				
				Global global = new Global(request);
				User u = global.getUser();
				
					StmtHelper.db("insert into form (title,iduser) values (").addVariable(formtitle)
						.addSql(",").addVariable(u.id).addSql(")").executeUpdate().provideTo(addContent).unsafeUpdate();
					StringBuffer sb = new StringBuffer();
					Map<String,String> formMap = new HashMap<String,String>();
					formMap.put("idform", String.valueOf(idform));
					formMap.put("content", content);
					formMap.put("formname", "Name Your Form");
					formMap.put("title", Option.fromString(formtitle).orSome(""));
					formMap.put("views","0");
					formMap.put("submissions", "0");
					FormsTable.getRow(formMap);
					data.put("content", content).put("link",link).put("addrow", sb.toString()).put("idform",idform).write(response.getWriter());
			}
			else
				data.write(response.getWriter());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
